package stock;

import java.util.ArrayList;
import java.util.List;

import misc.Helpers;

import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlTable;

public class LargeCap {

    private final List<String> largeCapList;

    private LargeCap() {
        System.out.println("Creating largecap list...");
        largeCapList = new ArrayList<String>();

        HtmlPage nordnetPage = getPage("https://www.nordnet.se/mux/web/marknaden/kurslista/aktier.html?marknad=Norden&Sverige=on&Finland=on&Norge=on&Danmark=on&large=on&sektor=0&subtyp=price&sortera=aktie&sorteringsordning=stigande");
        HtmlTable nordnetTable = (HtmlTable) nordnetPage
                .getByXPath(
                        "/html/body/div[@id='container']/div[@id='content']/div[@id='contentPadding']/table[@id='kurstabell']")
                .get(0);

        for (int i = 2; i < nordnetTable.getRowCount(); i++) {
            String name = nordnetTable.getCellAt(i, 1).asText().trim();
            name = Helpers.formatName(name);
            largeCapList.add(name);
        }

        HtmlPage avanzaPage = getPage("https://www.avanza.se/aza/aktieroptioner/kurslistor/kurslistor.jsp?cc=Norden&lkey=LargeCap");
        HtmlTable avanzaTable = (HtmlTable) avanzaPage
                .getByXPath(
                        "/html/body/table/tbody/tr[1]/td[1]/table[@class='tablecontent']/tbody/tr/td/table[@class='shareTable']")
                .get(0);

        for (int i = 2; i < avanzaTable.getRowCount(); i++) {
            String name = avanzaTable.getCellAt(i, 2).asText().trim();
            name = Helpers.formatName(name);
            largeCapList.add(name);
        }

    }

    public boolean isLargeCap(String name) {
        name = Helpers.formatName(name);
        return largeCapList.contains(name);
    }

    private HtmlPage getPage(String url) {
        WebClient client = Helpers.createNewAndSilenceWebClient();
        client.setJavaScriptEnabled(true);
        try {
            return (HtmlPage) client.getPage(url);
        } catch (Exception e) {
            e.printStackTrace();
            return getPage(url);
        }
    }

    private static class SingletonHolder {
        private static LargeCap instance = new LargeCap();
    }

    public static LargeCap getInstance() {
        return SingletonHolder.instance;
    }

}
